package com.dabai.iot.mqtt.server.verticle;

import io.vertx.core.Deployable;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.util.List;
import java.util.function.Supplier;

/**
 * 部署 MQTT 相关的 Verticle
 *
 * @author kev1n
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class MqttVerticleDeployer {

    private final Vertx vertx;
    private final List<Supplier<Deployable>> verticleSuppliers;

    @EventListener(ApplicationReadyEvent.class)
    public void deployVerticle() {
        for (Supplier<Deployable> verticleSupplier : verticleSuppliers) {
            if (verticleSupplier instanceof MqttVerticleSupplier) {
                DeploymentOptions options = new DeploymentOptions();
                options.setHa(true);
                options.setInstances(4);
                vertx.deployVerticle(verticleSupplier, options)
                    .onComplete(e -> {
                        if (e.succeeded()) {
                            log.info("MQTT Server ====> deploy verticle :{} success", verticleSupplier);
                        } else {
                            log.info("MQTT Server ====> deploy verticle :{} error", verticleSupplier, e.cause());
                        }
                    });
            } else if (verticleSupplier instanceof WebSocketVerticleSupplier) {
                DeploymentOptions options = new DeploymentOptions();
                vertx.deployVerticle(verticleSupplier, options)
                    .onComplete(e -> {
                        if (e.succeeded()) {
                            log.info("WS MQTT Server ====> deploy verticle :{} success", verticleSupplier);
                        } else {
                            log.info("WS MQTT Server ====> deploy verticle :{} error", verticleSupplier, e.cause());
                        }
                    });
            }
        }
    }
}
